<style>
  .import {
    opacity: 0;
    position: absolute;
    width: 69px;
    height: 38px;
    margin-left: -10px;
  }
</style>

<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <!-- 头部操作栏 -->
      <div class="layui-form lay-header">
        <div class="toolbar">
          <div class="layui-form-item lay-query-content">
            <div class="lay-query-box">
              <div class="query-lt">
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">工位名称：</label>
                  <div class="layui-input-inline">
                    <input name="name" class="layui-input" type="text" placeholder="请输入工位名称" autocomplete="off" />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">工位编号：</label>
                  <div class="layui-input-inline">
                    <input name="code" id="code" class="layui-input" type="text" placeholder="输入工位编号" autocomplete="off"  />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">是否启用：</label>
                  <div class="layui-input-inline">
                    <select name="isDeleted">
                      <option value="">请选择是否启用</option>
                      <option value="1">启用</option>
                      <option value="0">停用</option>
                    </select>
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">时间段：</label>
                  <div class="layui-input-inline">
                    <input name="createTime" id="pTime" class="layui-input date-icon" type="text" placeholder="选择时间" style="width: 200px" readonly />
                  </div>
                  <input name="startCreateTime" id="sTime" type="hidden" />
                  <input name="endCreateTime" id="eTime" type="hidden" />
                </div>
                <div class="layui-inline">
                  <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                  <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="lay-btn-rows">
          <div class="lay-btn-box">
            <div class="lay-btn-lt">
              <button id="deviceWorkshopBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
              <button id="uploaderInputBtn" class="layui-btn icon-btn color-reseda">
                <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx"/>导入
              </button>
              <button id="templateDownloadBtn" class="layui-btn icon-btn color-green">模版下载</button>
            </div>
            <div class="lay-btn-rt"></div>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <table class="layui-table" id="workStationTable" lay-filter="workStationTable"></table>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="workStationTableBar">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="workStationForm">
  <form lay-filter="workStationForm" class="layui-form model-form">
    <input name="id" type="hidden" />
    <div class="layui-form-item">
      <label class="layui-form-label">所在车间：</label>
      <div class="layui-input-block">
        <select name="workshopId" id="workshopId" lay-filter="workshopId" class="layui-input" type="text"></select>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">工位性质：</label>
      <div class="layui-input-block">
        <!--   <select name="nature" id="nature" class="layui-input"  lay-filter="nature"
                        type="text">
                </select>-->

        <select id="nature" name="nature" lay-filter="nature" class="common-select-search"></select>
      </div>
    </div>
    <div class="layui-form-item" id="spuDiv">
      <label class="layui-form-label">设备型号(设备SPU)：</label>
      <div class="layui-input-block">
        <select name="deviceModelSpuId" lay-search id="deviceModelSpuId" lay-filter="deviceModelSpuId" class="layui-input" type="text"></select>
      </div>
    </div>

    <div class="layui-form-item" id="skuDiv">
      <label class="layui-form-label">设备编号(设备SKU)：</label>
      <div class="layui-input-block">
        <select lay-search name="deviceSkuId" lay-filter="deviceSkuId" id="deviceSkuId" class="layui-input" type="text"></select>
      </div>
    </div>
    <!-- <div class="layui-form-item">
            <label class="layui-form-label">关联工站：</label>
            <div class="layui-input-block">
                <select name="workstationId" id="workstationId" class="layui-input"
                        type="text">
                </select>
            </div>
        </div> -->
    <div class="layui-form-item">
      <label class="layui-form-label">工位编号：</label>
      <div class="layui-input-block">
        <input name="code" placeholder="工位编号" type="text" class="layui-input" required autocomplete="off"  />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">工位名称：</label>
      <div class="layui-input-block">
        <input name="name" id="workStationName" placeholder="工位名称" type="text" class="layui-input" lay-verify="required" required autocomplete="off" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">责任工种：</label>
      <div class="layui-input-block">
        <select name="professionId" lay-search></select>
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">责任部门：</label>
      <div class="layui-input-block">
        <input id="departmentId" name="departmentId" type="hidden" />
        <input id="departmentName" name="departmentName" type="hidden" />
        <div id="departmentSearchClaim"></div>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">责任岗位：</label>
      <div class="layui-input-block">
        <select id="postId" name="postId" lay-filter="postId" class="common-select-search"></select>
        <input id="postName" name="postName" type="hidden" />
      </div>
    </div>
    <!--        <div class="layui-form-item">-->
    <!--            <label class="layui-form-label">状态：</label>-->
    <!--            <div class="layui-input-block">-->
    <!--                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="true" lay-text="启用|停用"/>-->
    <!--            </div>-->
    <!--        </div>-->

    <div class="layui-form-item">
      <label class="layui-form-label">备注：</label>
      <div class="layui-input-block">
        <input name="remark" placeholder="请输入备注" type="text" class="layui-input" />
      </div>
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" lay-filter="workStationFormSubmit" lay-submit>保存</button>
    </div>
  </form>
</script>

<!-- js部分 -->
<script>
  layui.use(["layer", "form", "table", "admin", "laydate"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var workshopRes;
    let deviceSkuRes;
    //时间范围
    laydate.render({
      elem: "#pTime",
      type: "date",
      range: true,
      done: function (value, date, endDate) {
        if (value) {
          var dateValue = value.split(" - ");
          $("#sTime").val(dateValue[0] + " 00:00:00");
          $("#eTime").val(dateValue[1] + " 23:59:59");
        } else {
          $("#sTime").val();
          $("#eTime").val();
        }
      }
    });

    // 渲染表格
    var insTb = table.render({
      elem: "#workStationTable",
      url: config.base + "enterprise/res/admin/setting/workStation/list",
      page: true,
      toolbar: true,
      defaultToolbar: ["filter"],
      cellMinWidth: 100,
      cols: [
        [
          { type: "numbers", title: "序号" },
          { field: "code", sort: false, title: "工位编号" },
          { field: "name", sort: false, title: "工位名称" },
          { field: "workshopName", sort: false, title: "所在车间" },
          { field: "natureName", sort: false, title: "工位性质" },
          // , {field: 'workstationName', sort: false, title: '关联工站'}
          { field: "postName", sort: false, title: "责任岗位" },
          { field: "professionName", sort: false, title: "工种名称" },
          { field: "deviceModelSpuNo", sort: false, title: "设备型号SPU" },
          { field: "deviceSkuCode", sort: false, title: "设备列表SKU" },
          {
            field: "isDeleted",
            sort: false,
            title: "是否启用",
            templet: function (d) {
              if (d.isDeleted) {
                return (
                  '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" checked="' + d.isDeleted + '" lay-filter="isDeleted"  lay-text="启用|停用"/>'
                );
              } else {
                return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" lay-filter="isDeleted"   lay-text="启用|停用"/>';
              }
            }
          },
          { field: "creatorName", sort: false, title: "创建人" },
          { field: "createTime", sort: false, title: "创建时间" },
          {
            align: "center",
            toolbar: "#workStationTableBar",
            title: "操作",
            width: 200
          }
        ]
      ],
      done: function (res, curr, count) {
        //移除按钮
        var menuButton = config.getMenuButton(location.hash);
        if (menuButton.indexOf("搜索") === -1) {
          $(".layui-form.toolbar").remove();
        }
        if (menuButton.indexOf("工位-变更") === -1) {
          $("[lay-event='edit']").remove();
        }
        if (menuButton.indexOf("删除") === -1) {
          $("[lay-event='del']").remove();
        }
      }
    });

    //启用/禁用
    form.on("switch(isDeleted)", function (obj) {
      if (obj.elem.checked) {
        enable(obj.value);
      } else {
        disable(obj.value);
      }
    });

    function enable(id) {
      admin.req(
        "enterprise/res/admin/setting/workStation/cancellation/" + id,
        null,
        function (res) {
          if (res.code === 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload("workStationTable");
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        "POST"
      );
    }

    function disable(id) {
      admin.req(
        "enterprise/res/admin/setting/workStation/recover/" + id,
        null,
        function (res) {
          if (res.code === 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload("workStationTable");
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        "POST"
      );
    }

    // 工具条点击事件
    table.on("tool(workStationTable)", function (obj) {
      var data = obj.data;
      if (obj.event === "edit") {
        //修改
        showEditModel(data);
      } else if (obj.event === "del") {
        // 删除
        doDelete(obj);
      }
    });

    // 搜索
    form.on("submit(formSubSearchLog)", function (data) {
      insTb.reload({ where: data.field, page: { curr: 1 } }, "data");
    });

    // 重置搜索
    form.on("submit(resets)", (data) => {
      $(".lay-header").find("select").val("");
      $(".lay-header").find("input").val("");
      let field = data.field;
      for (let key in field) {
        field[key] = "";
      }
      insTb.reload({ where: field, page: { curr: 1 } }, "data");
    });

    //监听排序
    table.on("sort(workStationTable)", function (obj) {
      table.reload("workStationTable", {
        initSort: obj,
        where: {
          sort: obj.field,
          order: obj.type
        }
      });
    });

    // 添加按钮点击事件
    $("#deviceWorkshopBtnAdd").click(function () {
      showEditModel();
    });

    // 显示编辑弹窗
    function showEditModel(data) {
      admin.open({
        type: 1,
        area: "620px",
        offset: "65px",
        title: data ? "修改工位信息" : "添加工位信息",
        content: $("#workStationForm").html(),
        success: async function () {
          if (data) {
            form.val("workStationForm", data);
            //工位性质
            admin.getDictList("nature", "station_nature_name", data.nature, "工位性质");
            await admin.initDataSelectPro(
              "enterprise/device/admin/device/list",
              {
                page: 1,
                limit: 999,
                deviceModelId: data.deviceModelId
              },
              "deviceSkuId",
              "设备编号(设备SKU)"
            );
            //所属车间
            admin.initDataSelect("enterprise/device/admin/deviceWorkshop/list?page=1&limit=999", null, "workshopId", data.workshopId, "车间", "name", "id");

            //岗位
            admin.initDataSelect("user/admin/role/getPostData", { roleId: data.departmentId }, "postId", data.postId, "岗位", null, null);

            //工站
            admin.initDataSelect("enterprise/res/admin/setting/workSite/list?page=1&limit=999", null, "workstationId", data.workstationId, "工站", "name", "id");

            admin.initDataSelectTree(true, "user/admin/role/getTreeData", null, "departmentSearchClaim", data.departmentId, "部门", "departmentId", function (data) {
              // 获取部门ID
              let departmentId = data.change[0].value;
              let departmentName = data.change[0].name;
              //赋值部门id
              $("#departmentId").val(departmentId);
              $("#departmentName").val(departmentName);
              $("#postId").empty();
              $("#postName").val("");
              //部门下的岗位列表
              admin.initDataSelect("user/admin/role/getPostData", { roleId: departmentId }, "postId", null, "岗位", null, null);
            });
            //设备型号 设备SPU  http://localhost:9300/enterprise/device/admin/deviceModel/list?page=1&limit=10

            if (data.professionId == undefined || data.professionId == null || data.professionId == "") {
              $("#spuDiv").hide();
              $("#skuDiv").hide();
            }
          } else {
            $("#spuDiv").hide();
            $("#skuDiv").hide();
            //部门列表
            admin.initDataSelectTree(true, "user/admin/role/getTreeData", null, "departmentSearchClaim", null, "部门", "departmentId", function (data) {
              // 获取部门ID
              let departmentId = data.change[0].value;
              let departmentName = data.change[0].name;
              //赋值部门id
              $("#departmentId").val(departmentId);
              $("#departmentName").val(departmentName);
              $("#postId").empty();
              $("#postName").val("");
              //部门下的岗位列表
              admin.initDataSelect("user/admin/role/getPostData", { roleId: departmentId }, "postId", null, "岗位", null, null);
            });

            //工位性质
            admin.getDictList("nature", "station_nature_name", null, "工位性质");

            //所属车间
            workshopRes = await admin.initDataSelectPro("enterprise/device/admin/deviceWorkshop/list?page=1&limit=999", {}, "workshopId", "车间", (d, obj) => {
              let deviceSkuObj = deviceSkuRes.find((v) => v.id == $("#deviceSkuId").val());
              if (deviceSkuObj) {
                $("#workStationName").val(obj.name + "-" + deviceSkuObj.name);
              } else {
                $("#workStationName").val("");
              }
            });

            //所属工位
            admin.initDataSelect("enterprise/res/admin/setting/workSite/list?page=1&limit=999", null, "workstationId", null, "工站", "name", "id");

            //设备型号 设备SPU  http://localhost:9300/enterprise/device/admin/deviceModel/list?page=1&limit=10
            //    admin.initDataSelect("enterprise/device/admin/deviceModel/list?page=1&limit=999", null, "deviceModelSpuId", null, "设备型号(设备SPU)", "name", "id");

            //  设备编号(设备SKU)
            //  admin.initDataSelect("enterprise/device/admin/device/list?page=1&limit=999", null, "deviceSkuId", null, "设备编号(设备SKU)", "name", "id");
          }

          // 设备型号 设备SPU

          // function initDeviceModelSpu(){
          //   let deviceModelSpuId = $("#deviceModelSpuId").val();
          //   let deviceSkuId = $("#deviceSkuId").val();
          //   if(deviceModelSpuId&&deviceSkuId){
          //     $("#workStationName").val(deviceModelSpuId+"-"+deviceSkuId);
          //   }
          // }

          await admin.initDataSelectPro(
            "enterprise/device/admin/deviceModel/list",
            {
              page: 1,
              limit: 999
            },
            "deviceModelSpuId",
            "设备型号(设备SPU)",
            async (d, obj) => {
              $("#workStationName").val("");

              deviceSkuRes = await admin.initDataSelectPro(
                "enterprise/device/admin/device/list",
                {
                  page: 1,
                  limit: 999,
                  deviceModelId: d.value
                },
                "deviceSkuId",
                "设备编号(设备SKU)",
                (d1, obj1) => {
                  let workshop = workshopRes.find((v) => v.id == $("#workshopId").val());
                  if (workshop) {
                    $("#workStationName").val(workshop.name + "-" + obj1.name);
                  }
                }
              );
            }
          );
          // admin.req(
          //   "enterprise/device/admin/deviceModel/list",
          //   { page: 1, limit: 999 },
          //   function (res) {
          //     if (res.code == 200) {
          //       var html = '<option value="">请选择设备型号(设备SPU)</option>';
          //       for (var k = 0; k < res.data.length; k++) {
          //         html +=
          //           '<option value="' +
          //           res.data[k].id +
          //           '">' +
          //           res.data[k].name +
          //           "</option>";
          //       }
          //       $("form select[name='deviceModelSpuId']").html(html);
          //       form.render("select");
          //       if (data && data.professionId) {
          //         form.val("workStationForm", data);
          //       }
          //     } else {
          //       layer.msg("获取设备编号(设备SKU)失败", { icon: 2, time: 1000 });
          //     }
          //   },
          //   "GET"
          // );

          // 设备编号(设备SKU)
          // admin.req(
          //   "enterprise/device/admin/device/list",
          //   { page: 1, limit: 999 },
          //   function (res) {
          //     if (res.code == 200) {
          //       var html = '<option value="">请选择设备编号(设备SKU)</option>';
          //       for (var k = 0; k < res.data.length; k++) {
          //         html +=
          //           '<option value="' +
          //           res.data[k].id +
          //           '">' +
          //           res.data[k].name +
          //           "</option>";
          //       }
          //       $("form select[name='deviceSkuId']").html(html);
          //       form.render("select");
          //       if (data && data.professionId) {
          //         form.val("workStationForm", data);
          //       }
          //     } else {
          //       layer.msg("获取设备编号(设备SKU)失败", { icon: 2, time: 1000 });
          //     }
          //   },
          //   "GET"
          // );

          // 获取负责人数据
          admin.req(
            "production/productionPlan/admin/profession/getAllProfession",
            {},
            function (res) {
              if (res.code == 200) {
                var html = '<option value="">请选择工种</option>';
                for (var k = 0; k < res.data.length; k++) {
                  html += '<option value="' + res.data[k].id + '">' + res.data[k].professionName + "</option>";
                }
                $("form select[name='professionId']").html(html);
                form.render("select");
                if (data && data.professionId) {
                  form.val("workStationForm", data);
                }
              } else {
                layer.msg("获取工种信息失败", { icon: 2, time: 1000 });
              }
            },
            "GET"
          );

          // 监听 select 的值改变
          form.on("select(postId)", function (data) {
            let selectedText = data.elem[data.elem.selectedIndex].text; // 获取选中的文本
            $("#postName").val(selectedText); // 打印显示的选项文本
          });

          form.on("select(nature)", function (data) {
            let selectedValue = data.value; // 获取选中的文本
            if (selectedValue == 1) {
              $("#spuDiv").show();
              $("#skuDiv").show();
              $("#workStationName").attr("disabled", true);
              $("#workStationName").attr("placeholder", "请选择所在车间和设备编号，自动生成。");
              console.log(111);
            } else {
              $("#spuDiv").hide();
              $("#skuDiv").hide();
              $("#workStationName").attr("disabled", false);
              $("#workStationName").attr("placeholder", "请输入工位名称");
            }
          });

          // 表单提交事件
          form.on("submit(workStationFormSubmit)", function (d) {
            layer.load(2);
            let formData = d.field;
            admin.req(
              data ? "enterprise/res/admin/setting/workStation/updateWorkStationBy" : "enterprise/res/admin/setting/workStation/addWorkStationBy",
              JSON.stringify(formData),
              function (res) {
                layer.closeAll("loading");
                if (res.code === 200) {
                  layer.msg(res.msg, { icon: 1 });
                  table.reload("workStationTable");
                  layer.closeAll("page");
                } else {
                  layer.msg(res.msg, { icon: 2 });
                }
              },
              data ? "PUT" : "POST",
              true,
              "application/json;charset=utf-8"
            );
            return false;
          });
        }
      });
    }

    // 删除
    function doDelete(obj) {
      layer.confirm(
        "确定要删除吗？",
        {
          offset: "65px",
          skin: "layui-layer-admin"
        },
        function (i) {
          layer.close(i);
          layer.load(2);
          admin.req(
            "enterprise/device/admin/deviceWorkshop/" + obj.data.id,
            {},
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                layer.msg(res.msg, { icon: 1 });
                obj.del();
              } else {
                layer.msg(res.msg, { icon: 2 });
              }
            },
            "DELETE"
          );
        }
      );
    }
    // 模板下载
    $('#templateDownloadBtn').click(function () {
      window.location.href = config.base + "enterprise/res/admin/setting/workStation/templateDownload";
    });

    // 导入excel
    $("#uploaderInput").on("change", function (e) {
      layer.load(2);
      var formData = new FormData();
      var files = e.target.files;
      let that = $(this);
      formData.append("file", files[0]);
      formData.append("name", files[0].name); //这个地方可以传递多个参数
      $.ajax({
        url: config.base + "enterprise/res/admin/setting/workStation/importExcel",
        data: formData,
        headers: { Authorization: "Bearer " + config.getToken() },
        type: "POST",
        processData: false,
        contentType: false,
        success: function (res) {
          layer.closeAll("loading");
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            layer.closeAll("page");
            setTimeout((_) => {
              location.reload();
            }, 1000);
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
          that.val("");
        },
      });
    });
  });
</script>
